<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\facade\Cache;
use app\admin\model\Config as ConfigModel;
use app\common\validate\ConfigValidate;

class Config extends Common {
	
	public function index(){
		return $this->fetch();
	}
	public function conflist(){
		$group = db('config_group')->select();
		// p($group);die;
		$this->assign('group',$group);
		return $this->fetch();
	}
	public function config_list(){
		$group_id = request()->param('group_id');
		$limit = request()->param('limit');
		$page = request()->param('page');
		$start = ($page-1)*$limit;
		$count = db('config')->where('group_id',$group_id)->count();
		$result = db('config')
				->alias('a')
				->join('field_type b','a.type_id = b.id')
				->where('a.group_id',$group_id)->limit($start,$limit)->order('a.id desc,a.sort desc')
				->field('a.id,a.name,a.title,a.remark,a.group_id,a.sort,b.title as type')
				->cache('config'.$group_id.$limit.$page,3600,'config')
				->select();
		
		return showTable(0, 'OK', $count ,$result, 200);
	}
	public function addconfig(){
		if(request()->isPost()){
			$data = request()->param();
			$validate = new ConfigValidate;
			if (!$validate->scene('add')->check($data)) {
				return show(0, $validate->getError(), 0 , 200);
			}else{
				if($data['t_value']){
					$str = str_replace("：",":",$data['t_value']);
					$data['t_value'] = $str;
				};
				Cache::clear('config'); 
				$rest = (new ConfigModel())->strict(false)->insert($data);
				return show(1, lang('add success'), $rest, 200);
			}
		}
		$group = db('config_group')->select();
		$type = db('field_type')->select();
		$this->assign('type',$type);
		$this->assign('group',$group);
		return $this->fetch();
	}
}
